package com.darchrow.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.darchrow.Constants;
import com.darchrow.mapper.OrderMapper;
import com.darchrow.mapper.TxLogMapper;
import com.darchrow.pojo.Order;
import com.darchrow.pojo.TxLog;
import com.darchrow.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.producer.TransactionSendResult;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;

/**
 * @author mdl
 * @date 2020/4/27 14:36
 */
@Slf4j
@Service
public class OrderServiceImpl implements OrderService {

    @Resource
    private RocketMQTemplate rocketMQTemplate;
    @Resource
    private OrderMapper orderMapper;
    @Resource
    private TxLogMapper txLogMapper;

    @Value("${rocketmq.trans-topic}")
    private String springTransTopic;


    @Override
    public void sendCreateOrderMsg(Order order) {
        String str = JSON.toJSONString(order);
        Message<String> message = MessageBuilder.withPayload(str).build();
        /**
         * 发送一条事务消息
         * String txProducerGroup: 生产组
         * String destination：topic
         * Message<?> message: 消息内容
         * Object arg: 参数
         */
        TransactionSendResult sendResult = rocketMQTemplate.sendMessageInTransaction(Constants.MQ_PRODUCER_GROUP, springTransTopic, message, null);
        log.info("输出生产者信息={}",sendResult);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void createOrder(Order order) {
        //用本地事务id幂等处理
        if (txLogMapper.selectById(order.getTxNum()) != null) {
            return;
        }
        orderMapper.insert(order);
        //插入事务日志
        TxLog txLog = new TxLog();
        txLog.setTxNum(order.getTxNum());
        System.out.println("order.getTxNum():" + order.getTxNum());
        txLog.setCreateTime(new Date());
        txLogMapper.insert(txLog);

        //模拟异常，检查事务是否回滚
        QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("commodity_code", "product-1");
        if (orderMapper.selectList(queryWrapper).size()== 20) {
            throw new RuntimeException("人为模拟异常");
        }
    }

}